class @AdminAuthorListingView extends ListingView
    
    el: $('#content')

    initialize: ->
        super
        @model.bind("change", @render)
        @model.fetch()
    
    render: ->
        @Navigate(@model.url(), false, true)
        @GetTemplate(SiteMap.Admin.Authors.ListingTemplate, (compiledTemplate) =>
            $(@el).html(compiledTemplate(@model.toJSON()))
        )

    events:
        "click .search": "search"
        "click .pagination a": "pagination"
        "click th>a": "sort"
        "click .buttons>.create": "create"
        "click .buttons>.delete": "remove"
        "click tbody tr>td:not(.chk)": "edit"
        "change .page-size": "changeSize"
        "click .reset": "reset"

    search: (event) ->
        event.preventDefault()

        firstName = $("#Filter_FirstName").val()
        lastName = $("#Filter_LastName").val()

        if (firstName? and firstName != '') || (lastName? and lastName != '')
            Messages.WriteMessage('Apply search.')
            Loading.Start()
            filter = @model.get("Filter")
            filter.LastName = lastName
            filter.FirstName = firstName
            @model.set("Filter", filter, { silent: true })
            @model.set("Page", 1, { silent: true })
            @model.fetch()

    reset: (event) ->
        Loading.Start()
        @model.set(
            "Filter"
            {
                LastName: ''
                FirstName: ''
            }
            silent: true
        )
        @model.set("Page", 1, { silent: true })
        @model.fetch()

    remove: (event) ->
        event.preventDefault()
        Messages.Clear()
        form = $(@el).find("form.listing")
        if form.find("input:checked").length
            confirmDialog = new AuthorDeleteConfirm(@)
            confirmDialog.Show("Are you sure?")
        else
            Messages.WriteMessage('Choose one or more authors.')

     create: (event) ->
        event.preventDefault()
        Loading.Start()
        @Navigate(SiteMap.Admin.Authors.Create, true)

class AuthorDeleteConfirm extends ConfirmDialog
    constructor: (view) ->
        @view = view
    Ok: ->
        form = $(@view.el).find("form.listing")
        data = form.serialize()
        Loading.Start()
        Messages.WriteMessage('Deleting authors.')
        $.post(SiteMap.Admin.Authors.Delete, data, (response) =>
            if (response.SuccessMessage? && response.SuccessMessage.length)
                Messages.WriteSuccessMessage(response.SuccessMessage)
                @view.model.fetch()
            else 
                Messages.WriteErrors(response.Errors)
                Loading.Stop()
        )